package com.lgy.sell.controller

import com.travel.api.beans.user.SysUser
import com.travel.api.service.user.UserService
import com.travel.api.utils.CommonUtil
import com.travel.api.utils.NetworkUtil
import com.travel.api.utils.RedisUtil
import org.apache.commons.lang3.StringUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@RestController
open class BaseController {

    @Autowired
    lateinit var userService: UserService

    companion object {

        private val TOKEN_PREFIX = "TOKEN::PREFIX::"
    }

    val log: Logger = LoggerFactory.getLogger(this::class.java)

    val servletRequestAttributes: ServletRequestAttributes
        get() = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes

    val httpServletRequest: HttpServletRequest
        get() = servletRequestAttributes.request

    val httpServletResponse: HttpServletResponse
        get() = servletRequestAttributes.response!!

    val ip: String
        get() {
            val ip = NetworkUtil.getIpAddress(httpServletRequest)
            return ip
        }

    fun success(): Map<String, Any> = CommonUtil.getSuccessResult()
    fun success(message: String?, data: Any?): Map<String, Any> = CommonUtil.getSuccessResult(message, data)

    fun fail(message: String?): Map<String, Any> = CommonUtil.getFailResult(message)
    fun fail(code: Int, message: String?): Map<String, Any> = CommonUtil.getFailResult(code, message)

    fun userInfo(): SysUser?{
        val token = httpServletRequest.getHeader("token")
        log.info("[TOKEN]: {}", token)
        if(StringUtils.isNotEmpty(token)) {
            val username = RedisUtil.get(TOKEN_PREFIX + token) // 获取用户账号
            if(StringUtils.isNotEmpty(username)) {
                // 查询用户信息
                val userInfo = userService.getUserInfo(mobile = username)
                log.info("[用户信息]: {}", userInfo)
                return userInfo
            }
        }
        return null
    }
}